package SimulatorComponents;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import DataFormatConversionComponents.NumberConverter;
import Exceptions.InvalidMemoryAllocationException;
import StorageComponents.Memory;

/**
 * This class loads the main memory with the input file that is going to be used to test
 * the simulator. 
 *
 */
public class MemoryLoader {

	private int instructionCount = 0;
	/**
	 * Loads input file into memory in the first 127 addresses
	 * @param mem the memory where the file is to be stored
	 * @throws FileNotFoundException
	 */
	public int load(Memory mem) throws FileNotFoundException, InvalidMemoryAllocationException{

		Scanner in = new Scanner( new File("/home/mpc/workspace/arkilloso/src/arki/test_file") );
		NumberConverter converter = new NumberConverter();
		int[] temp;
		int address = 0;
		
		while( in.hasNext() ){
			if( address > 127 )      
				throw new InvalidMemoryAllocationException("Cannot load entire input file. Current address is: " +
						address +" > maximun allowed (127).");					
			String line = in.next();
			temp = converter.hexToBinary(line);
			System.out.print("\n");

			mem.writeWord(temp, address);
			address += 2;
			instructionCount++;
		}

		return instructionCount;
		
	}
}
